package org.wjw.base.exception.handle;

import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.wjw.base.exception.BusinessException;
import org.wjw.base.exception.ErrorCode;
import org.wjw.base.util.AjaxResult;

import java.util.List;

@RestControllerAdvice
//全局异常处理
public class GlobalExceptionHandler {
    //处理BusinessException
    @ExceptionHandler(BusinessException.class)
    public AjaxResult businessExceptionHandler(BusinessException e){
        e.printStackTrace();
        return AjaxResult.me().setSuccess(false)
                .setCode(e.getCode()).setMessage(e.getMessage());
    }
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public AjaxResult methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e){
        e.printStackTrace();
        BindingResult bindingResult = e.getBindingResult();
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        StringBuilder sb = new StringBuilder();
        fieldErrors.forEach(fieldError -> {
            sb.append(fieldError.getDefaultMessage()+",");
        });
        String message = sb.substring(0,sb.length()-1);
        return AjaxResult.me().setSuccess(false)
                .setMessage(message).setCode(ErrorCode.CODE_400.getCode());
    }
    @ExceptionHandler(Exception.class)
    public AjaxResult exceptionHandler(Exception e){
        e.printStackTrace();
        return AjaxResult.me().setSuccess(false).setMessage(ErrorCode.CODE_500.getMessage()).
                setCode(ErrorCode.CODE_500.getCode());
    }
}
